#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
飞书多维表格商品管理系统示例
展示如何使用飞书多维表格API构建一个完整的商品管理系统
"""

import json
import time
from datetime import datetime
from typing import Dict, List, Optional, Any
from feishu_bitable_client import FeishuBitableClient
from config import config

class GoodsManager:
    """商品管理系统"""
    
    def __init__(self, client: FeishuBitableClient, app_token: str, table_id: str):
        self.client = client
        self.app_token = app_token
        self.table_id = table_id
    
    def add_product(self, name: str, price: float, category: str, stock: int, description: str = "") -> Dict[str, Any]:
        """添加商品"""
        fields = {
            "商品名称": name,
            "价格": price,
            "分类": category,
            "库存": stock,
            "描述": description,
            "创建时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "状态": "在售"
        }
        
        return self.client.create_record(
            app_token=self.app_token,
            table_id=self.table_id,
            fields=fields
        )
    
    def update_product_price(self, record_id: str, new_price: float) -> Dict[str, Any]:
        """更新商品价格"""
        fields = {
            "价格": new_price,
            "更新时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        return self.client.update_record(
            app_token=self.app_token,
            table_id=self.table_id,
            record_id=record_id,
            fields=fields
        )
    
    def update_stock(self, record_id: str, new_stock: int) -> Dict[str, Any]:
        """更新库存"""
        fields = {
            "库存": new_stock,
            "更新时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        # 根据库存自动更新状态
        if new_stock <= 0:
            fields["状态"] = "缺货"
        elif new_stock <= 10:
            fields["状态"] = "库存不足"
        else:
            fields["状态"] = "在售"
        
        return self.client.update_record(
            app_token=self.app_token,
            table_id=self.table_id,
            record_id=record_id,
            fields=fields
        )
    
    def search_products_by_category(self, category: str) -> List[Dict[str, Any]]:
        """按分类搜索商品"""
        # 构建过滤条件
        filter_condition = f'CurrentValue.[分类] = "{category}"'
        
        result = self.client.search_records(
            app_token=self.app_token,
            table_id=self.table_id,
            filter_condition=filter_condition,
            page_size=100
        )
        
        if result.get('code') == 0:
            return result.get('data', {}).get('items', [])
        return []
    
    def search_low_stock_products(self, threshold: int = 10) -> List[Dict[str, Any]]:
        """搜索库存不足的商品"""
        filter_condition = f'CurrentValue.[库存] <= {threshold}'
        
        result = self.client.search_records(
            app_token=self.app_token,
            table_id=self.table_id,
            filter_condition=filter_condition,
            page_size=100
        )
        
        if result.get('code') == 0:
            return result.get('data', {}).get('items', [])
        return []
    
    def get_product_statistics(self) -> Dict[str, Any]:
        """获取商品统计信息"""
        # 获取所有商品
        result = self.client.search_records(
            app_token=self.app_token,
            table_id=self.table_id,
            page_size=1000
        )
        
        if result.get('code') != 0:
            return {"error": "获取数据失败"}
        
        products = result.get('data', {}).get('items', [])
        
        # 统计信息
        stats = {
            "总商品数": len(products),
            "在售商品数": 0,
            "缺货商品数": 0,
            "库存不足商品数": 0,
            "总库存价值": 0,
            "分类统计": {},
            "平均价格": 0
        }
        
        total_price = 0
        
        for product in products:
            fields = product.get('fields', {})
            status = fields.get('状态', '')
            category = fields.get('分类', '未分类')
            price = fields.get('价格', 0)
            stock = fields.get('库存', 0)
            
            # 状态统计
            if status == '在售':
                stats["在售商品数"] += 1
            elif status == '缺货':
                stats["缺货商品数"] += 1
            elif status == '库存不足':
                stats["库存不足商品数"] += 1
            
            # 分类统计
            if category not in stats["分类统计"]:
                stats["分类统计"][category] = 0
            stats["分类统计"][category] += 1
            
            # 价格和库存统计
            total_price += price
            stats["总库存价值"] += price * stock
        
        # 计算平均价格
        if len(products) > 0:
            stats["平均价格"] = round(total_price / len(products), 2)
        
        return stats
    
    def batch_update_category_prices(self, category: str, price_multiplier: float) -> List[Dict[str, Any]]:
        """批量更新某分类商品的价格"""
        # 先搜索该分类的所有商品
        products = self.search_products_by_category(category)
        results = []
        
        for product in products:
            record_id = product.get('record_id')
            current_price = product.get('fields', {}).get('价格', 0)
            new_price = round(current_price * price_multiplier, 2)
            
            result = self.update_product_price(record_id, new_price)
            results.append({
                'record_id': record_id,
                'old_price': current_price,
                'new_price': new_price,
                'result': result
            })
            
            # 避免请求过于频繁
            time.sleep(0.1)
        
        return results
    
    def export_products_to_json(self, filename: str = None) -> str:
        """导出商品数据到JSON文件"""
        if filename is None:
            filename = f"products_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        # 获取所有商品
        result = self.client.search_records(
            app_token=self.app_token,
            table_id=self.table_id,
            page_size=1000
        )
        
        if result.get('code') != 0:
            raise Exception(f"导出失败: {result}")
        
        products = result.get('data', {}).get('items', [])
        
        # 整理数据格式
        export_data = {
            "export_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "total_count": len(products),
            "products": []
        }
        
        for product in products:
            export_data["products"].append({
                "record_id": product.get('record_id'),
                "fields": product.get('fields', {})
            })
        
        # 保存到文件
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(export_data, f, indent=2, ensure_ascii=False)
        
        return filename

def main():
    """商品管理系统主函数"""
    print("🛍️ 飞书多维表格商品管理系统")
    print("=" * 50)
    
    # 验证配置
    if not config.validate():
        config.print_config_help()
        return
    
    # 创建客户端
    client = FeishuBitableClient(
        client_id=config.CLIENT_ID,
        client_secret=config.CLIENT_SECRET,
        redirect_uri=config.REDIRECT_URI
    )
    
    # 确保有有效的访问令牌
    print("\n🔐 正在获取访问令牌...")
    if not client.ensure_valid_token():
        print("❌ 无法获取访问令牌，请检查配置")
        return
    
    print("✅ 成功获取访问令牌")
    
    # 获取多维表格信息
    print("\n📋 请输入多维表格信息：")
    app_token = input("请输入多维表格的app_token: ").strip()
    table_id = input("请输入数据表的table_id: ").strip()
    
    if not app_token or not table_id:
        print("❌ app_token和table_id不能为空")
        return
    
    # 创建商品管理器
    goods_manager = GoodsManager(client, app_token, table_id)
    
    # 主菜单循环
    while True:
        print("\n" + "=" * 50)
        print("🛍️ 商品管理系统菜单：")
        print("1. 添加商品")
        print("2. 更新商品价格")
        print("3. 更新库存")
        print("4. 按分类搜索商品")
        print("5. 查看库存不足商品")
        print("6. 查看商品统计")
        print("7. 批量更新分类价格")
        print("8. 导出商品数据")
        print("0. 退出")
        
        choice = input("\n请输入选项 (0-8): ").strip()
        
        try:
            if choice == '0':
                print("👋 再见！")
                break
            elif choice == '1':
                add_product_interactive(goods_manager)
            elif choice == '2':
                update_price_interactive(goods_manager)
            elif choice == '3':
                update_stock_interactive(goods_manager)
            elif choice == '4':
                search_by_category_interactive(goods_manager)
            elif choice == '5':
                show_low_stock_products(goods_manager)
            elif choice == '6':
                show_statistics(goods_manager)
            elif choice == '7':
                batch_update_prices_interactive(goods_manager)
            elif choice == '8':
                export_data_interactive(goods_manager)
            else:
                print("❌ 无效选项，请重新选择")
                
        except Exception as e:
            print(f"❌ 操作失败: {e}")
        
        input("\n按回车键继续...")

def add_product_interactive(manager: GoodsManager):
    """交互式添加商品"""
    print("\n➕ 添加商品")
    
    name = input("商品名称: ").strip()
    if not name:
        print("❌ 商品名称不能为空")
        return
    
    try:
        price = float(input("价格: ").strip())
        stock = int(input("库存: ").strip())
    except ValueError:
        print("❌ 价格和库存必须是数字")
        return
    
    category = input("分类: ").strip()
    description = input("描述 (可选): ").strip()
    
    print("\n正在添加商品...")
    result = manager.add_product(name, price, category, stock, description)
    
    if result.get('code') == 0:
        record = result.get('data', {}).get('record', {})
        print(f"\n✅ 商品添加成功！")
        print(f"  记录ID: {record.get('record_id')}")
        print(f"  商品信息: {json.dumps(record.get('fields', {}), indent=2, ensure_ascii=False)}")
    else:
        print(f"❌ 添加失败: {result}")

def update_price_interactive(manager: GoodsManager):
    """交互式更新价格"""
    print("\n💰 更新商品价格")
    
    record_id = input("请输入商品记录ID: ").strip()
    if not record_id:
        print("❌ 记录ID不能为空")
        return
    
    try:
        new_price = float(input("新价格: ").strip())
    except ValueError:
        print("❌ 价格必须是数字")
        return
    
    print("\n正在更新价格...")
    result = manager.update_product_price(record_id, new_price)
    
    if result.get('code') == 0:
        print("✅ 价格更新成功！")
    else:
        print(f"❌ 更新失败: {result}")

def update_stock_interactive(manager: GoodsManager):
    """交互式更新库存"""
    print("\n📦 更新商品库存")
    
    record_id = input("请输入商品记录ID: ").strip()
    if not record_id:
        print("❌ 记录ID不能为空")
        return
    
    try:
        new_stock = int(input("新库存: ").strip())
    except ValueError:
        print("❌ 库存必须是整数")
        return
    
    print("\n正在更新库存...")
    result = manager.update_stock(record_id, new_stock)
    
    if result.get('code') == 0:
        print("✅ 库存更新成功！")
    else:
        print(f"❌ 更新失败: {result}")

def search_by_category_interactive(manager: GoodsManager):
    """交互式按分类搜索"""
    print("\n🔍 按分类搜索商品")
    
    category = input("请输入分类名称: ").strip()
    if not category:
        print("❌ 分类名称不能为空")
        return
    
    print(f"\n正在搜索分类 '{category}' 的商品...")
    products = manager.search_products_by_category(category)
    
    if products:
        print(f"\n✅ 找到 {len(products)} 个商品：")
        for i, product in enumerate(products, 1):
            fields = product.get('fields', {})
            print(f"\n商品 {i}:")
            print(f"  ID: {product.get('record_id')}")
            print(f"  名称: {fields.get('商品名称', 'N/A')}")
            print(f"  价格: {fields.get('价格', 'N/A')}")
            print(f"  库存: {fields.get('库存', 'N/A')}")
            print(f"  状态: {fields.get('状态', 'N/A')}")
    else:
        print(f"❌ 未找到分类 '{category}' 的商品")

def show_low_stock_products(manager: GoodsManager):
    """显示库存不足的商品"""
    print("\n⚠️ 库存不足商品")
    
    try:
        threshold = int(input("请输入库存阈值 (默认10): ").strip() or "10")
    except ValueError:
        threshold = 10
    
    print(f"\n正在搜索库存少于 {threshold} 的商品...")
    products = manager.search_low_stock_products(threshold)
    
    if products:
        print(f"\n⚠️ 找到 {len(products)} 个库存不足的商品：")
        for i, product in enumerate(products, 1):
            fields = product.get('fields', {})
            print(f"\n商品 {i}:")
            print(f"  ID: {product.get('record_id')}")
            print(f"  名称: {fields.get('商品名称', 'N/A')}")
            print(f"  当前库存: {fields.get('库存', 'N/A')}")
            print(f"  状态: {fields.get('状态', 'N/A')}")
    else:
        print(f"✅ 没有库存少于 {threshold} 的商品")

def show_statistics(manager: GoodsManager):
    """显示商品统计信息"""
    print("\n📊 商品统计信息")
    print("正在获取统计数据...")
    
    stats = manager.get_product_statistics()
    
    if "error" in stats:
        print(f"❌ 获取统计信息失败: {stats['error']}")
        return
    
    print("\n📊 统计结果：")
    print(f"  总商品数: {stats['总商品数']}")
    print(f"  在售商品数: {stats['在售商品数']}")
    print(f"  缺货商品数: {stats['缺货商品数']}")
    print(f"  库存不足商品数: {stats['库存不足商品数']}")
    print(f"  总库存价值: ¥{stats['总库存价值']:.2f}")
    print(f"  平均价格: ¥{stats['平均价格']:.2f}")
    
    print("\n📈 分类统计：")
    for category, count in stats['分类统计'].items():
        print(f"  {category}: {count} 个商品")

def batch_update_prices_interactive(manager: GoodsManager):
    """交互式批量更新价格"""
    print("\n💰 批量更新分类价格")
    
    category = input("请输入要更新的分类名称: ").strip()
    if not category:
        print("❌ 分类名称不能为空")
        return
    
    try:
        multiplier = float(input("请输入价格倍数 (如1.1表示涨价10%): ").strip())
    except ValueError:
        print("❌ 价格倍数必须是数字")
        return
    
    confirm = input(f"确认要将分类 '{category}' 的所有商品价格乘以 {multiplier} 吗？(y/N): ").strip().lower()
    if confirm != 'y':
        print("❌ 操作已取消")
        return
    
    print(f"\n正在批量更新分类 '{category}' 的商品价格...")
    results = manager.batch_update_category_prices(category, multiplier)
    
    if results:
        print(f"\n✅ 批量更新完成，共处理 {len(results)} 个商品：")
        for result in results:
            status = "成功" if result['result'].get('code') == 0 else "失败"
            print(f"  商品ID {result['record_id']}: {result['old_price']} -> {result['new_price']} ({status})")
    else:
        print(f"❌ 未找到分类 '{category}' 的商品")

def export_data_interactive(manager: GoodsManager):
    """交互式导出数据"""
    print("\n📤 导出商品数据")
    
    filename = input("请输入导出文件名 (可选，默认自动生成): ").strip()
    filename = filename if filename else None
    
    print("\n正在导出数据...")
    try:
        exported_file = manager.export_products_to_json(filename)
        print(f"✅ 数据导出成功！")
        print(f"  文件名: {exported_file}")
    except Exception as e:
        print(f"❌ 导出失败: {e}")

if __name__ == "__main__":
    main()